package com.trust.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.trust.agri.util.BeanUtil;
import com.trust.entity.FarmCollect;
import com.trust.entity.Param.FarmCollectListParam;
import com.trust.entity.VO.FarmCollectListVO;
import com.trust.mapper.FarmCollectMapper;
import com.trust.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class FarmCollectServiceImpl extends ServiceImpl<FarmCollectMapper, FarmCollect> implements FarmCollectService {


    @Resource
    private FarmPlantService farmPlantService;

    @Resource
    private FarmSeedService farmSeedService;

    @Resource
    private SystemDepartmentService systemDepartmentService;

    @Resource
    private SystemPersonService systemPersonService;

    @Override
    public Page<FarmCollectListVO> list(FarmCollectListParam param) {
        LambdaQueryWrapper<FarmCollect> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getCode())){
            wrapper.like(FarmCollect::getCode, param.getCode());
        }
        wrapper.eq(ObjectUtil.isNotEmpty(param.getType()), FarmCollect::getType, param.getType());
        if (null != param.getStartTime() && null != param.getEndTime()){
            wrapper.and(e -> {
                e.or(f -> {
                    f.between(FarmCollect::getStartTime, param.getStartTime(), param.getEndTime());
                });
                e.or(f -> {
                    f.between(FarmCollect::getEndTime, param.getStartTime(), param.getEndTime());
                });
            });
        }
        wrapper.orderByDesc(FarmCollect::getId);
        Page<FarmCollect> page = this.page(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);
        Page<FarmCollectListVO> targetPage = BeanUtil.sourcePage2targetPage(page, FarmCollectListVO.class);
        for (FarmCollectListVO record : targetPage.getRecords()) {
            if (record.getType() == 1){
                //种植
                record.setCategoryName(farmPlantService.getCateNameById(record.getPlantId()));
                record.setUnit("kg");
                record.setTypeName("种植采收");
            } else if (record.getType() == 2){
                //育苗
                record.setCategoryName(farmSeedService.getCateNameById(record.getPlantId()));
                record.setUnit("株");
                record.setTypeName("育苗采收");
            }
            record.setDeptName(systemDepartmentService.getNameById(record.getDeptId()));
            record.setPrincipal(systemPersonService.getNameById(record.getPrincipalId()));
        }
        return targetPage;
    }
}
